﻿using Autofac;
using Autofac.Extras.DynamicProxy;
using DiffuseEnjoyIdle.Core.Aop;
using log4net;
using Mapster;
using System.Reflection;

namespace DiffuseEnjoyIdle.Extension.Extensions
{
    public class AutofacModuleRegister : Autofac.Module
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(AutofacModuleRegister));

        protected override void Load(ContainerBuilder builder)
        {
            var basePath = AppContext.BaseDirectory;

            #region 带有接口层的服务注入

            var servicesDllFile = Path.Combine(basePath, "DiffuseEnjoyIdle.Service.dll");
            var repositoryDllFile = Path.Combine(basePath, "DiffuseEnjoyIdle.Repository.dll");
            var messageCenterDllFile = Path.Combine(basePath, "DiffuseEnjoyIdle.MessageCenter.dll");
            var timedTaskCenterDllFile = Path.Combine(basePath, "DiffuseEnjoyIdle.TimedTaskCentre.dll");
            if (!(File.Exists(servicesDllFile) && File.Exists(repositoryDllFile) && File.Exists(messageCenterDllFile)))
            {
                var msg = "Repository.dll、Service.dll和MessageCenter.dll丢失，因为项目解耦了，所以需要先F6编译，再F5运行，请检查 bin 文件夹，并拷贝。";
                log.Error(msg);
                throw new Exception(msg);
            }
            builder.RegisterType<TransactionAop>();

            // 获取 Service.dll 程序集服务，并注册
            var assemblysServices = Assembly.LoadFrom(servicesDllFile);
            builder.RegisterAssemblyTypes(assemblysServices)
                      .AsImplementedInterfaces()
                      .InstancePerDependency()
                      .InterceptedBy(typeof(TransactionAop));

            // 获取 Repository.dll 程序集服务，并注册
            var assemblysRepository = Assembly.LoadFrom(repositoryDllFile);
            builder.RegisterAssemblyTypes(assemblysRepository)
                   .AsImplementedInterfaces()//以接口的方式注入
                   .InstancePerDependency();//找到所有被实现的接口注入

            // 获取 messageCenter.dll 程序集服务，并注册
            var messageCenter = Assembly.LoadFrom(messageCenterDllFile);
            builder.RegisterAssemblyTypes(messageCenter)
                   .AsImplementedInterfaces()
                   .InstancePerDependency();

            // 获取 timedTaskCentre.dll 程序集服务，并注册
            var timedTaskCentre = Assembly.LoadFrom(timedTaskCenterDllFile);
            builder.RegisterAssemblyTypes(timedTaskCentre)
                   .AsImplementedInterfaces()
                   .InstancePerDependency();

            //var config = new TypeAdapterConfig();//注册Mapster映射配置
            //config.Scan(GetType().GetTypeInfo().Assembly);

            #endregion 带有接口层的服务注入
        }
    }
}